sharing\natives\windows/
singleton.rs

1/*
2 * Authors: Jorge.A Duran & Mario Gónzalez
3 * Company: pispas Technologies SL
4 * Date: April 23, 2023
5 * Description: Singleton definition and implementation.
6 */
7
8use crate::natives::api::MutexHandle;
9use crate::natives::api::NativeResult;
10
11#[derive(Clone, Debug)]
12pub struct SingleInstance {
13    handle: MutexHandle,
14}
15
16unsafe impl Send for SingleInstance {}
17
18impl crate::natives::api::Lock for SingleInstance {
19    fn lock(&self) -> NativeResult<()> {
20        if self.handle.is_null() {
21            anyhow::bail!("Unable to get singleton handle")
22        }
23
24        let result = unsafe {crate::natives::api::wait_for_single_object(self.handle, 0u32)};
25        match result {
26            crate::natives::api::ResultCode::Abandoned => {
27                anyhow::bail!("singleton was owned from another pid")
28            }
29            _ => {}
30        };
31
32        Ok(())
33    }
34
35    fn unlock(&self) -> Result<(), anyhow::Error> {
36        unsafe{
37            crate::natives::api::release_mutex(self.handle);
38        }
39        
40        Ok(())
41    }
42}
43
44impl Drop for SingleInstance {
45    fn drop(&mut self) {
46        if !self.handle.is_null() {
47            unsafe {
48                crate::natives::api::close_handle(self.handle);    
49            }
50        }
51    }
52}
53
54impl SingleInstance {
55    pub fn new(key: &str) -> SingleInstance {
56        let handle = crate::natives::api::create_mutex(key);
57        SingleInstance { handle }
58    }
59
60    pub fn clear(_key: &str) -> NativeResult<()> {
61        Ok(())
62    }
63}